﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;

using System.Windows.Forms;
using DevExpress.Utils.Drawing.Helpers;
using MINERP.BLL.NewPB;
using MINERP.ComControls;
using MINERP.MODEL.FoundationModel;
using MINERP.MODEL.NewPinBan;
using MINERP.NewPB.com;
using MINERP.NewPB.Forms;
using MINERP.NewPB.IView;
using RealLayoutPanel;
using System.Linq;

namespace MINERP.NewPB.Presenter
{
  

    internal class MyPhotoSizeComparer : IEqualityComparer<string>
    {
        #region IEqualityComparer<string> 成员

        public bool Equals(string x, string y)
        {
            string[] xWH = x.Split(new[] {
											'*'
										});
            string[] yWH = y.Split(new[] {
											'*'
										});
            if ((xWH[0] == yWH[0] && xWH[1] == yWH[1]) || (xWH[0] == yWH[1] && xWH[1] == yWH[0]))
            {
                return true;
            }
            return false;
        }
        public int GetHashCode(string obj)
        {
            //return obj.GetHashCode();
            return -1;
        }

        #endregion
    }

    public class MainPresenter
    {
        #region private fields

        private readonly List<PicView> _ListPicView = new List<PicView>(); //用于存放被拖到大纸上所有的图片集合
        private readonly AutoPB _autoPb;
        private readonly NewPBBLL _bll;
        private readonly IMainView _view;
        private Point _PicEnablePoint = new Point(-1, -1); //在拖动释放的那一刻，图片能放到的有效的坐标
        private List<PhotoInfo_PinBan> _clearBoxPhotos = new List<PhotoInfo_PinBan>(); //清柜的那些照片,暂时无用
        private int _curMaxX; //当前最大的X值
        private List<PhotoInfo_PinBan> _curShowPhotoList; //当前照片列表中列出的照片列表
        private float _curWraste; //当前浪费率
        private bool _isNewPhotoList; //照片列表是否是新的，即主要是不同的打印机、纸型、纸面决定了照片列表是否是新的
        private List<PicView> _mulSelPicVList; //被多选的那些图片的集合
        private PicView _multilSelectTPicV; //存入多选后形成的那个大的PICV
        private List<string> _photoSizeList = new List<string>(); //存放照片尺寸列表
        private List<PhotoInfo_PinBan> _photosList; //存放所有照片的列表，各种过滤前的总照片列表

        #endregion

        public MainPresenter(IMainView view)
        {



            otherMatPhotoInfo = new List<PhotoInfo_PinBan>();
            _view = view;
            _bll = new NewPBBLL();
            _autoPb = new AutoPB();
            _autoPb.BARCODEWIDTH2 = DataTransfer.BarCodePixWidth;
            _bll.BARCODEWIDTH = DataTransfer.BarCodePixWidth;
            IntilView();
            _bll.CurentPrinter = DataTransfer.CurPrinter;
        }

        #region help methods

        private void GetSuitPoint(PicView pv) //得到符合大纸范围的合适的坐标
        {
            Point p = pv.Location;
            if (p.X < 0)
            {
                p.X = 0;
            }
            if (pv.Location.Y < 0)
            {
                p.Y = 0;
            }
            if (p.Y + pv.Height > DataTransfer.inchBoardHeight)
            {
                p.Y = DataTransfer.inchBoardHeight - pv.Height;
            }
            if (pv.Right > DataTransfer.inchBoardWidth && pv.Left <= DataTransfer.inchBoardWidth) //判断是否压红线
            {
                p.X = DataTransfer.inchBoardWidth + 10;
                //p.Y = (p.Y < 0)||(p.Y>DataTransfer.inchBoardHeight) ? 10 : p.Y;
            }
            pv.Location = p;
        }
        private bool GetSuitPoint(ref Point p, PicView pv) //得到符合大纸范围的合适的坐标,能否找到合适的位置
        {
            bool result = true;
            if (p.X < 0)
            {
                p.X = 0;
            }
            if (p.Y < 0)
            {
                p.Y = 0;
            }
            if (p.Y + pv.Height > DataTransfer.inchBoardHeight)
            {
                if (DataTransfer.inchBoardHeight - pv.Height < 0)
                {
                    return false;
                }
                p.Y = DataTransfer.inchBoardHeight - pv.Height;
            }

            //if (pv.Right > DataTransfer.inchBoardWidth && pv.Left <= DataTransfer.inchBoardWidth)//判断是否压红线
            //{
            //    p.X = DataTransfer.inchBoardWidth + 10;
            //    p.Y = (p.Y < 0) || (p.Y > DataTransfer.inchBoardHeight) ? 10 : p.Y;
            //}
            return result;
        }
        public void SetWraste(float wraste)
        {
            _curWraste = wraste;
            ShowWraste();
        }
        private void ShowWraste() //显示浪费率
        {
            //			int effectArea, MaxX, totalArea; //有效面积与最大X值、以及总面积 
            Color wTextColor = Color.Orange; //浪费率的显示颜色
            //			_curMaxX = MaxX;
            //			totalArea = MaxX*DataTransfer.inchBoardHeight;
            //			wraste = 1 - (effectArea/(float) totalArea);
            //			_curWraste = wraste;
            if (_curWraste > 0.1)
            {
                wTextColor = Color.Red;
            }
            _view.ShowWaste(string.Format("{0:0.00}%", _curWraste * 100), wTextColor);
        }
        private void BindPhotos(List<PhotoInfo_PinBan> sourcePList)
        {
            _view.BindMainGrid(sourcePList);
            BindShopList(sourcePList);
            BindPhotoSizeList(sourcePList);
        }
        private void BindDefaultPhotos() //默认绑定当前主GRIDVIEW中的照片列表
        {
            _view.BindMainGrid(_curShowPhotoList);
            BindShopList(_curShowPhotoList);
            BindPhotoSizeList(_curShowPhotoList);
        }
        private void BindShopList(IEnumerable<PhotoInfo_PinBan> sourcePList) //绑定商户列表
        {
            List<BindShopInfo> listBindShop = new List<BindShopInfo>();
            foreach (IGrouping<string, PhotoInfo_PinBan> item in sourcePList.GroupBy(p => p.ShopName))
            {
                BindShopInfo shopInfo = new BindShopInfo { ShopName = item.Key };
                shopInfo.Ctms = new List<BindCtmInfo>();
                foreach (string ctmName in item.Select(p => p.CtmName).Distinct())
                {
                    BindCtmInfo ctmInfo = new BindCtmInfo { CtmName = ctmName };
                    ctmInfo.OrderProductS = item.Where(p => p.CtmName == ctmName).Select(p => p.OrderInfoName).Distinct().ToList();
                    ctmInfo.OrderList = new List<BindOrderInfo>();
                    foreach (string orderName in ctmInfo.OrderProductS)
                    {
                        var currList = item.Where(p => p.CtmName == ctmName && p.OrderInfoName == orderName);
                        ctmInfo.OrderList.Add(new BindOrderInfo
                        {
                            IsPriority =
                               currList.Max(p => p.Priority) >= 6 ||
                              currList.Count(cc=>cc.IsRebackPhoto) > 0,
                            OrderProductName = orderName,
                            IsPart = currList.Count(s => s.isPart) > 0
                        });
                    }
                    shopInfo.Ctms.Add(ctmInfo);
                }
                listBindShop.Add(shopInfo);
            }
            _view.BindShopList(listBindShop);
        }
        private void BindPhotoSizeList(IEnumerable<PhotoInfo_PinBan> sourcePList) //绑定尺寸列表
        {
            _photoSizeList =
                sourcePList.Select(p => p.PhotoSize)
                            .Distinct(new MyPhotoSizeComparer())
                            .OrderBy(s => Convert.ToSingle(s.Substring(0, s.IndexOf("*"))))
                            .ThenBy(s => Convert.ToSingle(s.Substring(s.IndexOf("*") + 1)))
                            .ToList();
            _view.BindPhotoSizeList(_photoSizeList);
        }

        //private void GetSuitPhotosByTemplate() //根据当前的模板得到合适的照片列表
        //{
        //    _bll.PBorderNum = DataTransfer.ShowOrderNum;
        //    _photosList = _bll.GetAllPhotos(DataTransfer.CurPrinter.PrinterID, DataTransfer.curTemplate.PaperTypeId, DataTransfer.curTemplate.PaperFaceId);
        //    _curShowPhotoList = _photosList;
        //}
        private void GetSuitPhotosByTemplate(bool showAllPapertypePhotos) //根据当前的模板得到合适的照片列表
        {
            _bll.PBorderNum = DataTransfer.ShowOrderNum;
            _photosList = _bll.GetAllPhotos(DataTransfer.CurPrinter.PrinterID, DataTransfer.curTemplate.PaperTypeId, DataTransfer.curTemplate.PaperFaceId, DataTransfer.curTemplate.TempLateId, showAllPapertypePhotos,
                                            DataTransfer.CurPrinter,0).OrderByDescending(od=>od.Priority).ThenBy(or=>or.PhotoId).ToList();
            _curShowPhotoList = _photosList;
        }
        private void IntilView() //初始化界面元素
        {
            FrmSelectPrinter frmSel = new FrmSelectPrinter();
            while (DataTransfer.CurPrinter == null)
            {
                frmSel.ShowDialog();
            }
            ShowStatusMsg();
            _view.InitCtlsLoaction();
            _view.DrawScaleLine();

            //绑定模板列表
            BindTemplate();
        }
        private void ShowStatusMsg() //在状态栏显示Msg主要是操作员、打印机、是否有条码
        {
            string msg = "操作员：" + DataTransfer.curUser + "    | 当前设备：" + DataTransfer.CurPrinter.PName + "   |" +
                        (DataTransfer.curTemplate.HasBarCode == false ? "有条码" : "无条码");
            _view.ShowStatusMsg(msg);
        }
        private void BindTemplate() //绑定模板
        {
            if (DataTransfer.TemplateList == null || DataTransfer.TemplateList.Count < 1)
            {
                DataTransfer.TemplateList = _bll.GetAllTemplate(DataTransfer.CurPrinter.PrinterID);
            }
            _view.BindCmbTempate(DataTransfer.TemplateList);
        }
        private void ResolveAutoPBResult(List<PhotoInfo_PinBan> listResult)
        { //解析自动拼板的结果（主要是用来显示在大纸上）
            RectangeView[] arrayRect = new RectangeView[listResult.Count];
            for (int i = 0; i < listResult.Count; i++)
            {
                arrayRect[i].BarcodePixelWidth = DataTransfer.BarCodePixWidth;
                arrayRect[i].BarcodePlace = listResult[i].BarCodeStatus;
                arrayRect[i].DPI = DataTransfer.CurPrinter.PDPI;
                arrayRect[i].filename = listResult[i].PicPath;
                arrayRect[i].isRotate = Convert.ToInt32(listResult[i].IsWhirl);
                arrayRect[i].PictureHeight = Convert.ToInt32((decimal)listResult[i].Height * DataTransfer.CurPrinter.PDPI);
                arrayRect[i].PictureID = listResult[i].PhotoId;
                arrayRect[i].PictureWidth = Convert.ToInt32((decimal)listResult[i].Width * DataTransfer.CurPrinter.PDPI);
                arrayRect[i].PixelX = listResult[i].Location.X;
                arrayRect[i].PixelY = listResult[i].Location.Y;
                //arrayRect[i].
                //arrayRect[i].Unit = toolStripComboBoxUnit.SelectedIndex;
            }
            Array array = arrayRect;
            _view.ShowPic(array);
            ShowWraste();
        }

        #endregion

        private void picV_KeyPress(object sender, KeyPressEventArgs e) //旋转、删除操作
        {
            PicView picCur = (PicView)sender;
            if (e.KeyChar == (int)Keys.Space) //旋转
            {
                #region 旋转方向

                //PicView picCur = (PicView)sender;
                if (picCur.Type == 1) //多选中的temp大图
                {
                    return;
                }
                int newWidth = 0, newHeight = 0;
                PicView tempPic;
                bool isRect;

                //if (DataTransfer.curTemplate.HasBarCode)//有条码
                //{
                if (picCur.PInfo.BarCodeStatus == 1)
                {
                    newWidth = picCur.Height + DataTransfer.BarCodePixWidth;
                    newHeight = picCur.Width - DataTransfer.BarCodePixWidth;
                }
                else if (picCur.PInfo.BarCodeStatus == 0)
                {
                    newWidth = picCur.Height - DataTransfer.BarCodePixWidth;
                    newHeight = picCur.Width + DataTransfer.BarCodePixWidth;
                }

                    //}
                else //无条码
                {
                    newWidth = picCur.Height;
                    newHeight = picCur.Width;
                }
                tempPic = new PicView(picCur.PInfo.PhotoId, newWidth, newHeight, picCur.Location);
                Point pt = tempPic.Location;
                bool result = GetSuitPoint(ref pt, tempPic);
                if (result == false)
                {
                    tempPic.Dispose();
                    return;
                }
                tempPic.Location = pt;
                isRect = IsInRect(tempPic);
                if (!isRect)
                {
                    picCur.Location = tempPic.Location;
                    picCur.Width = newWidth;
                    picCur.Height = newHeight;
                    picCur.IsWhirl = !picCur.IsWhirl;
                    ShowWraste();
                }
                tempPic.Dispose();

                #endregion
            }
            else if (e.KeyChar == 100 || e.KeyChar == (int)Keys.Delete || e.KeyChar == (int)Keys.D) //删除
            {
                #region 删除选中图片

                //PicView picCur = (PicView)sender;
                if (picCur.Type == 1) //多选删除
                {
                    if (_mulSelPicVList != null && _mulSelPicVList.Count > 1)
                    {
                        foreach (PicView pic in _mulSelPicVList)
                        {
                            PhotoInfo_PinBan pi = _photosList.FirstOrDefault(p => p.PhotoId == pic.PInfo.PhotoId);
                            if (pi != null)
                            {
                                pi.IsInBoard = false;
                                pi.IsWhirl = false;
                            }
                            _ListPicView.Remove(pic);
                            pic.Dispose();
                        }
                        _mulSelPicVList.Clear();
                        _multilSelectTPicV.Dispose();
                        _multilSelectTPicV = null;
                        picCur.Dispose();
                        _ListPicView.Remove(picCur);
                    }
                }
                else //单选删除
                {
                    PhotoInfo_PinBan pi = _photosList.FirstOrDefault(p => p.PhotoId == picCur.PInfo.PhotoId);
                    if (pi != null)
                    {
                        pi.IsInBoard = false;
                        pi.IsWhirl = false;
                        picCur.Dispose();
                    }
                    _ListPicView.Remove(picCur);
                }
                _view.RefushMainGrid();
                ShowWraste();

                #endregion
            }
            else if (e.KeyChar == (int)Keys.F || e.KeyChar == 102) //将条码在上下部或是左右部切换
            {
                #region 切换条码的方向

                if (picCur.Type == 1) //多选中的temp大图
                {
                    return;
                }
                if (picCur.PInfo.BarCodeStatus != 2) //有条码
                {
                    int newWidth = 0, newHeight = 0, tempBarCodeStatus = picCur.PInfo.BarCodeStatus;
                    PicView tempPic;
                    bool isRect;
                    if (picCur.PInfo.BarCodeStatus == 1) //条码在左右,切换到上下
                    {
                        newWidth = picCur.Width - DataTransfer.BarCodePixWidth;
                        newHeight = picCur.Height + DataTransfer.BarCodePixWidth;
                        tempBarCodeStatus = 0;
                    }
                    else //条码在上下,切换到左右
                    {
                        newWidth = picCur.Width + DataTransfer.BarCodePixWidth;
                        newHeight = picCur.Height - DataTransfer.BarCodePixWidth;
                        tempBarCodeStatus = 1;
                    }
                    tempPic = new PicView(picCur.PInfo.PhotoId, newWidth, newHeight, picCur.Location);
                    Point pt = tempPic.Location;
                    bool result = GetSuitPoint(ref pt, tempPic);
                    if (result == false)
                    {
                        tempPic.Dispose();
                        return;
                    }
                    tempPic.Location = pt;
                    isRect = IsInRect(tempPic);
                    if (!isRect)
                    {
                        picCur.Location = tempPic.Location;
                        picCur.Width = newWidth;
                        picCur.Height = newHeight;
                        picCur.PInfo.BarCodeStatus = tempBarCodeStatus;
                        ShowWraste();
                    }
                    tempPic.Dispose();
                }

                #endregion
            }
            else if (e.KeyChar == (int)Keys.T || e.KeyChar == 116) //选中的图片之打印一张图片的条码，其它照片无条码
            {
                #region

                if (picCur.Type == 1)
                {
                    if (_mulSelPicVList != null && _mulSelPicVList.Count > 1)
                    {
                        if (MessageBox.Show("确定要将选中的照片只打印一张条码？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                        {
                            return;
                        }
                        bool isSet = false;
                        foreach (PicView pic in _mulSelPicVList)
                        {
                            if (!isSet)
                            {
                                if (pic.PInfo.BarCodeStatus != 2)
                                {
                                    isSet = true;
                                }
                                continue;
                            }

                            //OrderInfo_PB_Info oi = _allOrderList.FirstOrDefault(o => o.order_Base_Info.OrderProductId == pic.PInfo.Photo_Base_Info.OrderProductId);
                            //if (oi != null)
                            //{
                            //PhotoInfo_PB pi = oi.PhotoList.FirstOrDefault(p => p.PhotoId == pic.PInfo.PhotoId);

                            //if (pi != null)
                            //{
                            int newWidth = 0, newHeight = 0;
                            if (pic.PInfo.BarCodeStatus == 1) //条码在左右,切换到无条码
                            {
                                newWidth = pic.Width - DataTransfer.BarCodePixWidth;
                                newHeight = pic.Height;
                            }
                            else //条码在上下,切换到无条码
                            {
                                newWidth = pic.Width;
                                newHeight = pic.Height - DataTransfer.BarCodePixWidth;
                            }
                            pic.Width = newWidth;
                            pic.Height = newHeight;
                            pic.PInfo.BarCodeStatus = 2;
                            //}
                            //}
                        }
                    }
                }

                #endregion
            }
        }
        private void _lblPSize_MouseDown(object sender, MouseEventArgs e)
        {
            picV_MouseDown(((Control)sender).Parent, e);
        }
        private void _lblPName_MouseDown(object sender, MouseEventArgs e)
        {
            picV_MouseDown(((Control)sender).Parent, e);
        }
        internal void AutoSelectedCurGridThreePicToBoard() //自动从当前列表中远定三张照片放到大板上
        {
            if (_ListPicView.Count > 0)
            {
                PhotoInfo_PinBan[] photoInfoPinBans = _curShowPhotoList.Where(p => !p.IsInBoard).Take(5).ToArray();
                _view.AddPicToBand(photoInfoPinBans);
            }
            else
            {
                PhotoInfo_PinBan[] photoInfoPinBans = _curShowPhotoList.Where(p => !p.IsInBoard).ToArray();
                _view.AddPicToBand(photoInfoPinBans);
            }
            _view.RefushMainGrid();
        }
        public void ChangePhotoStatus(int[] photoIDArray, bool b)
        {
            if (photoIDArray != null && _photosList != null)
            {
                foreach (int photoid in photoIDArray)
                {
                    PhotoInfo_PinBan photoInfo = _photosList.FirstOrDefault(p => p.PhotoId == photoid);
                    if (photoInfo != null)
                    {
                        photoInfo.IsInBoard = b;
                    }
                }
            }
        }

        #region 拖动图片

        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;
        [DllImport("user32")]
        public static extern int IntersectRect(ref NativeMethods.RECT lpDestRect, ref NativeMethods.RECT lpSrc1Rect,
                                                ref NativeMethods.RECT lpSrc2Rect);
        private void picV_PicMoveEvent(PicView sender, Point newPoint) //移动图片
        {
            Point CurPoint = newPoint;
            Point controlLocation = sender.Parent.PointToClient(CurPoint); //当前PIC控件在PANEL中的location相对坐标位置
            GetSuitPoint(ref controlLocation, sender);
            if (sender.LeftAnchor || sender.RightAnchor)
            {
                controlLocation.X = sender.Left;
            }
            if (sender.UpAnchor || sender.DownAnchor)
            {
                controlLocation.Y = sender.Top;
            }
            PicView _tempPicView = new PicView(sender.PInfo.PhotoId, sender.Width, sender.Height, controlLocation);
            bool result = false;
            List<PicView> overPicList = null; //如果重叠的话，记录重叠的图片集合
            if (!_tempPicView.IsOutRedLine) //红线外的不管
            {
                result = IsInRect(_tempPicView);
            }
            else
            {
                controlLocation = _tempPicView.Location;
            }
            if (result) //如果虚线框与其它图片重叠
            {
                #region //如果虚线框与其它图片重叠

                Point factPoint = sender.Location; //实框的坐标
                DirEmu direction = GetLoctionDirection(controlLocation, factPoint); //虚线框在实框的什么方位
                PicView overPic = null;
                switch (direction)
                {
                    case DirEmu.LeftUp:

                        #region 左上

                        sender.RightAnchor = false;
                        sender.DownAnchor = false;
                        while (factPoint.X - controlLocation.X > 1 || factPoint.Y - controlLocation.Y > 1)
                        {
                            //if (sender.LeftAnchor && sender.UpAnchor)
                            //{
                            //    break;//上和左边都靠上了，再往左上移就不动
                            //}
                            if (!sender.LeftAnchor)
                            {
                                if (factPoint.X > 0)
                                {
                                    factPoint.X -= 1;
                                }
                                else
                                {
                                    factPoint.X = 0;
                                    sender.LeftAnchor = true;
                                }
                            }
                            if (!sender.UpAnchor)
                            {
                                if (factPoint.Y > 0)
                                {
                                    factPoint.Y -= 1;
                                }
                                else
                                {
                                    factPoint.Y = 0;
                                    sender.UpAnchor = true;
                                }
                            }
                            _tempPicView.Location = factPoint;
                            overPicList = _ListPicView.OrderByDescending(pv => pv.Right).OrderByDescending(pv => pv.Bottom).ToList();
                            //bool hasOver = IsInRect(_tempPicView, ListPicView, out overPic);
                            bool hasOver = IsInRect(_tempPicView, overPicList, out overPic);
                            if (hasOver)
                            {
                                #region 如果有重叠,就先退回到不重叠的状态，再看与重叠图片的位置关系，再决定是左靠还是右靠还是上靠还是下靠

                                if (!sender.LeftAnchor)
                                {
                                    factPoint.X += 1;
                                }
                                if (!sender.UpAnchor)
                                {
                                    factPoint.Y += 1;
                                }
                                _tempPicView.Location = factPoint;
                                DirEmu dire = GetTwoPicVRelativelyDir(_tempPicView, overPic);
                                switch (dire)
                                {
                                    case DirEmu.Left:
                                        sender.LeftAnchor = true;
                                        break;
                                    case DirEmu.Right:
                                        sender.RightAnchor = true;
                                        break;
                                    case DirEmu.Up:
                                        sender.UpAnchor = true;
                                        break;
                                    case DirEmu.Down:
                                        sender.DownAnchor = true;
                                        break;
                                }
                                break;

                                #endregion
                            }
                        }
                        sender.Location = factPoint;

                        #endregion

                        break;
                    case DirEmu.LeftDown:

                        #region 左下

                        sender.RightAnchor = false;
                        sender.UpAnchor = false;
                        while (factPoint.X - controlLocation.X > 1 || controlLocation.Y - factPoint.Y > 1)
                        {
                            if (!sender.LeftAnchor)
                            {
                                if (factPoint.X > 0)
                                {
                                    factPoint.X -= 1;
                                }
                            }
                            if (!sender.DownAnchor)
                            {
                                if (factPoint.Y < DataTransfer.inchBoardHeight)
                                {
                                    factPoint.Y += 1;
                                }
                                else
                                {
                                    factPoint.Y = DataTransfer.inchBoardHeight;
                                    sender.DownAnchor = true;
                                }
                            }
                            _tempPicView.Location = factPoint;
                            overPicList = _ListPicView.OrderByDescending(pv => pv.Right).OrderBy(pv => pv.Top).ToList();
                            bool hasOver = IsInRect(_tempPicView, overPicList, out overPic);
                            if (hasOver)
                            {
                                #region 如果有重叠,就先退回到不重叠的状态，再看与重叠图片的位置关系，再决定是左靠还是右靠还是上靠还是下靠

                                if (!sender.LeftAnchor)
                                {
                                    factPoint.X += 1;
                                }
                                if (!sender.DownAnchor)
                                {
                                    factPoint.Y -= 1;
                                }
                                _tempPicView.Location = factPoint;
                                DirEmu dire = GetTwoPicVRelativelyDir(_tempPicView, overPic);
                                switch (dire)
                                {
                                    case DirEmu.Left:
                                        sender.LeftAnchor = true;
                                        break;
                                    case DirEmu.Right:
                                        sender.RightAnchor = true;
                                        break;
                                    case DirEmu.Up:
                                        sender.UpAnchor = true;
                                        break;
                                    case DirEmu.Down:
                                        sender.DownAnchor = true;
                                        break;
                                }
                                break;

                                #endregion
                            }
                        }
                        sender.Location = factPoint;

                        #endregion

                        break;
                    case DirEmu.RightDown:

                        #region 右下

                        sender.LeftAnchor = false;
                        sender.UpAnchor = false;
                        while (controlLocation.X - factPoint.X > 1 || controlLocation.Y - factPoint.Y > 1)
                        {
                            if (!sender.RightAnchor)
                            {
                                factPoint.X += 1;
                            }
                            if (!sender.DownAnchor)
                            {
                                if (factPoint.Y < DataTransfer.inchBoardHeight)
                                {
                                    factPoint.Y += 1;
                                }
                                else
                                {
                                    factPoint.Y = DataTransfer.inchBoardHeight;
                                    sender.DownAnchor = true;
                                }
                            }
                            _tempPicView.Location = factPoint;
                            overPicList = _ListPicView.OrderBy(pv => pv.Left).ThenBy(pv => pv.Top).ToList();
                            bool hasOver = IsInRect(_tempPicView, overPicList, out overPic);
                            if (hasOver)
                            {
                                #region 如果有重叠,就先退回到不重叠的状态，再看与重叠图片的位置关系，再决定是左靠还是右靠还是上靠还是下靠

                                if (!sender.RightAnchor)
                                {
                                    factPoint.X -= 1;
                                }
                                if (!sender.DownAnchor)
                                {
                                    factPoint.Y -= 1;
                                }
                                _tempPicView.Location = factPoint;
                                DirEmu dire = GetTwoPicVRelativelyDir(_tempPicView, overPic);
                                Debug.WriteLine("重叠的照片ID：" + overPic.PInfo.PhotoId);
                                switch (dire)
                                {
                                    case DirEmu.Left:
                                        sender.LeftAnchor = true;
                                        break;
                                    case DirEmu.Right:
                                        sender.RightAnchor = true;
                                        break;
                                    case DirEmu.Up:
                                        sender.UpAnchor = true;
                                        break;
                                    case DirEmu.Down:
                                        sender.DownAnchor = true;
                                        break;
                                }
                                break;

                                #endregion
                            }
                        }
                        sender.Location = factPoint;

                        #endregion

                        break;
                    case DirEmu.RightUp:

                        #region 右上

                        sender.DownAnchor = false;
                        sender.LeftAnchor = false;
                        while (controlLocation.X - factPoint.X > 1 || factPoint.Y - controlLocation.Y > 1)
                        {
                            if (!sender.RightAnchor)
                            {
                                factPoint.X += 1;
                            }
                            if (!sender.UpAnchor)
                            {
                                if (factPoint.Y > 0)
                                {
                                    factPoint.Y -= 1;
                                }
                                else
                                {
                                    factPoint.Y = 0;
                                    sender.UpAnchor = true;
                                }
                            }
                            _tempPicView.Location = factPoint;
                            overPicList = _ListPicView.OrderBy(pv => pv.Left).OrderByDescending(pv => pv.Bottom).ToList();
                            bool hasOver = IsInRect(_tempPicView, overPicList, out overPic);
                            if (hasOver)
                            {
                                #region 如果有重叠,就先退回到不重叠的状态，再看与重叠图片的位置关系，再决定是左靠还是右靠还是上靠还是下靠

                                if (!sender.RightAnchor)
                                {
                                    factPoint.X -= 1;
                                }
                                if (!sender.UpAnchor)
                                {
                                    factPoint.Y += 1;
                                }
                                _tempPicView.Location = factPoint;
                                DirEmu dire = GetTwoPicVRelativelyDir(_tempPicView, overPic);
                                switch (dire)
                                {
                                    case DirEmu.Left:
                                        sender.LeftAnchor = true;
                                        break;
                                    case DirEmu.Right:
                                        sender.RightAnchor = true;
                                        break;
                                    case DirEmu.Up:
                                        sender.UpAnchor = true;
                                        break;
                                    case DirEmu.Down:
                                        sender.DownAnchor = true;
                                        break;
                                }
                                break;

                                #endregion
                            }
                        }
                        sender.Location = factPoint;

                        #endregion

                        break;
                }

                #endregion
            }
            else
            {
                sender.Location = controlLocation;
                sender.LeftAnchor = false;
                sender.RightAnchor = false;
                sender.UpAnchor = false;
                sender.DownAnchor = false;
            }
            _PicEnablePoint = sender.Location;
        }
        /// <summary>
        ///     得到pv2相对于pv1的相对位置，这二个图都相邻且不相交的，上、下、左、右,pV1是移动的那图片，PV2是与PV1重叠的，即PV1要靠上PV2
        ///     Pv1是不与PV2重叠前的最近的那个图形
        /// </summary>
        /// <param name="pv1"></param>
        /// <param name="pv2"></param>
        /// <returns></returns>
        private DirEmu GetTwoPicVRelativelyDir(PicView pv1, PicView pv2)
        {
            if (pv1.Left >= pv2.Right)
            {
                return DirEmu.Left;
            }
            if (pv1.Right <= pv2.Left)
            {
                return DirEmu.Right;
            }
            if (pv1.Top >= pv2.Bottom)
            {
                return DirEmu.Up;
            }
            if (pv1.Bottom <= pv2.Top)
            {
                return DirEmu.Down;
            }
            return 0;
        }
        /// <summary>
        ///     得到p1相对于P2的方位,左上、左下、右上、右下
        /// </summary>
        /// <param name="p1">虚线框的Location</param>
        /// <param name="p2">实框的Location</param>
        /// <returns></returns>
        private DirEmu GetLoctionDirection(Point p1, Point p2)
        {
            if (p1.X <= p2.X)
            {
                if (p1.Y <= p2.Y)
                {
                    return DirEmu.LeftUp;
                }
                return DirEmu.LeftDown;
            }
            if (p1.Y <= p2.Y)
            {
                return DirEmu.RightUp;
            }
            return DirEmu.RightDown;
        }
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        private void picV_MouseDown(object sender, MouseEventArgs e) //按下左键，准备移动
        {
            if (e.Button == MouseButtons.Left)
            {
                PicView _curPicView; //当前被选中的要进行移动的图片          
                _curPicView = (PicView)sender;
                if (_curPicView.Type == 0 && _multilSelectTPicV != null)
                {
                    CancelMutilSelect();
                }
                _curPicView.Focus();
                _curPicView.Select();

                //启动移动图片
                ReleaseCapture();
                SendMessage(_curPicView.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
                if (_PicEnablePoint.X != -1)
                {
                    _curPicView.Location = _PicEnablePoint;
                }
                _PicEnablePoint = new Point(-1, -1);
                _curPicView.LeftAnchor = false;
                _curPicView.RightAnchor = false;
                _curPicView.UpAnchor = false;
                _curPicView.DownAnchor = false;
                ShowWraste();
            }
        }

        /// <summary>
        ///     方向
        /// </summary>
        private enum DirEmu
        {
            LeftUp = 1, //左上
            LeftDown = 2, //左下
            RightDown = 3, //右下
            RightUp = 4, //右上
            Left = 5,
            Right,
            Up,
            Down
        }

        #region 是否重叠

        private PicView _RedPicView; //代码红线的矩形框
        /// <summary>
        ///     判断图片是否和tarGetList集合中的有重叠
        /// </summary>
        /// <param name="pv"></param>
        /// <param name="tarGetList"></param>
        /// <param name="overPic">和PV重叠的那张图片</param>
        /// <returns></returns>
        public bool IsInRect(PicView pv, List<PicView> tarGetList, out PicView overPic)
        {
            bool result = false;
            if (pv.IsOverRedLin)
            {
                if (_RedPicView == null)
                {
                    _RedPicView = new PicView(0, 1, DataTransfer.inchBoardHeight, new Point(DataTransfer.inchBoardWidth, 0));
                }
                overPic = _RedPicView;
                //overPic = new PicView(0, 1, DataTransfer.inchBoardHeight, new Point(DataTransfer.inchBoardWidth, 0));
                return true;
            }
            overPic = null;
            NativeMethods.RECT rectResult = new NativeMethods.RECT(); //如果相交的话，此值就不为空
            NativeMethods.RECT curtRect = new NativeMethods.RECT(pv.Rect);
            foreach (PicView picV in tarGetList)
            {
                if (picV.PInfo.PhotoId != pv.PInfo.PhotoId && picV.IsOutRedLine == false && picV.Type != 2)
                {
                    NativeMethods.RECT PicVRect = new NativeMethods.RECT(picV.Rect);
                    int res = IntersectRect(ref rectResult, ref PicVRect, ref curtRect);
                    if (res > 0)
                    {
                        result = true;
                        overPic = picV;
                        break;
                    }
                }
            }
            return result;
        }
        /// <summary>
        ///     查看图片是否超出了边界
        /// </summary>
        /// <param name="pv"></param>
        /// <returns></returns>
        private bool IsOverBoard(PicView pv)
        {
            if (pv.Location.X < 0)
            {
                return true;
            }
            if (pv.Location.Y < 0)
            {
                return true;
            }
            if (pv.Location.Y + pv.Height > DataTransfer.inchBoardHeight)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        ///     判断图片是否与其它已存在的图片重叠
        /// </summary>
        /// <param name="pv"></param>
        /// <param name="overPicList">与PV重叠的那些图片集合</param>
        /// <returns></returns>
        public bool IsInRect(PicView pv)
        {
            bool result = false;
            //先得判断是否出拼板区的边界
            if (IsOverBoard(pv))
            {
                return true;
            }
            if (pv.IsOverRedLin)
            {
                return true;
            }
            NativeMethods.RECT rectResult = new NativeMethods.RECT(); //如果相交的话，些值就不为空
            NativeMethods.RECT curtRect = new NativeMethods.RECT(pv.Rect);
            foreach (PicView picV in _ListPicView)
            {
                if (picV.PInfo.PhotoId != pv.PInfo.PhotoId && picV.IsOutRedLine == false && picV.Type != 2)
                {
                    NativeMethods.RECT PicVRect = new NativeMethods.RECT(picV.Rect);
                    int res = IntersectRect(ref rectResult, ref PicVRect, ref curtRect);
                    if (res > 0)
                    {
                        result = true;
                        break;
                    }
                }
            }
            return result;
        }

        #endregion

        #endregion 移动图片

        #region public methods

        //private List<PicView> _OveredPointList = new List<PicView>();
        /// <summary>
        ///     已被放了图片的坐标点
        /// </summary>
        /// <summary>
        ///     将托动到大板上的图片放到一个最合适的位置
        /// </summary>
        /// <param name="picV"></param>
        /// <param name="pinfo"></param>
        private void SetPicAtSuitPostion(PicView picV)
        {
            bool isSuss = false;
            //所有可能的坐标
            List<Point> LocationList = new List<Point>();
            LocationList.Add(new Point(0, 0));
            foreach (PicView pic in _ListPicView.Where(p => !p.IsOutRedLine).ToList())
            {
                LocationList.Add(pic.Point2);
                LocationList.Add(pic.Point4);
                LocationList.Add(new Point(pic.Point2.X, 0));
                LocationList.Add(new Point(0, pic.Point4.Y));
            }
            LocationList = LocationList.Except(_ListPicView.Where(p => !p.IsOutRedLine).Select(p => p.Location).ToList()).ToList();
            //清除重复
            LocationList = LocationList.Distinct().ToList();
            //排序
            LocationList = LocationList.OrderBy(p => p.X).ThenBy(p => p.Y).ToList();
            foreach (Point point in LocationList)
            {
                picV.Location = point;
                if (IsInRect(picV)) //如果重叠，就旋转一下再试
                {
                    picV = CircumrotatePic(picV);
                    if (IsInRect(picV)) //如果旋转,还是重叠，则应旋转回来，再继续试下一下结点
                    {
                        picV = CircumrotatePic(picV);
                    }
                    if (!picV.IsWhirl)
                    {
                        picV.IsWhirl = true;
                    }
                    else
                    {
                        picV.IsWhirl = false;
                    }
                    isSuss = true;
                    break;
                }
                isSuss = true;
                break;
            }
            if (!isSuss) //如果全部试完都还没有成功，则将图片放到红线外
            {
                picV.Location = new Point(DataTransfer.inchBoardWidth + 10, 5);
            }
            AddPicToPanel(picV);
        }
        /// <summary>
        ///     将一个图片放到大板上
        /// </summary>
        /// <param name="picV"></param>
        /// <param name="pinfo"></param>
        public void AddPicToPanel(PicView picV)
        {
            _ListPicView.Add(picV);
            picV.PInfo.IsInBoard = true;
            //						picV.MouseDown += picV_MouseDown;
            //						picV.PicMoveEvent += picV_PicMoveEvent;
            //						picV.KeyPress += picV_KeyPress;
            //						picV._lblPName.MouseDown += _lblPName_MouseDown;
            //						picV._lblPSize.MouseDown += _lblPSize_MouseDown;
            //			_view.ShowPic(picV);
            ShowWraste();
        }
        public void AddPicToPanel(int p)
        {
            PhotoInfo_PinBan photoInfoPinBan = _curShowPhotoList.First(c => c.PhotoId == p);
            //			AddPicToPanel(new PicView(photoInfoPinBan,));
        }
        public void AddPicToPanel(int[] picidArray)
        {
        }
        /// <summary>
        ///     旋转图片
        /// </summary>
        /// <param name="oldPic"></param>
        /// <returns></returns>
        private PicView CircumrotatePic(PicView oldPic)
        {
            //旋转后再试
            int width, height;
            width = oldPic.Width;
            height = oldPic.Height;
            if (DataTransfer.BarCodeStatus == 1) //条码在左右
            {
                width -= DataTransfer.BarCodePixWidth;
                height += DataTransfer.BarCodePixWidth;
            }
            else if (DataTransfer.BarCodeStatus == 0) //条码在上下
            {
                width += DataTransfer.BarCodePixWidth;
                height -= DataTransfer.BarCodePixWidth;
            }
            oldPic.Width = height;
            oldPic.Height = width;
            return oldPic;
        }
        //		internal void NewDrawPic(List<PhotoInfo_PinBan> photoList, Point mouseFormBigBoardPoint) {
        //			int overPicCount = 1; //一次拖多张图片放到拼板区或时，如果出现重叠，则将图片放到红线右边上时需要有一个减
        //			//按照高宽大小排倒序
        //			photoList = photoList.OrderByDescending(p => p.Height).ThenByDescending(p => p.Width).ToList();
        //			foreach(var pinfo in photoList) {
        //				//if(pinfo.PixHeight>)
        //								var picV = new PicView(pinfo, mouseFormBigBoardPoint);
        //				var tempPoint = pinfo.Location;
        //				if (DataTransfer.PhotoDirection == 0) {
        //				}
        //				else if (DataTransfer.PhotoDirection == 1) //横向
        //				{
        //					if (pinfo.PixHeight > pinfo.PixWidth) {
        //						picV = CircumrotatePic(picV);
        //						picV.IsWhirl = true;
        //					}
        //				}
        //				else if (DataTransfer.PhotoDirection == 2) {
        //					if (pinfo.PixHeight < pinfo.PixWidth) {
        //						picV = CircumrotatePic(picV);
        //						picV.IsWhirl = true;
        //					}
        //				}
        //				if (!GetSuitPoint(ref tempPoint, picV)) {
        //					//旋转后再试
        //					picV = CircumrotatePic(picV);
        //					if (!GetSuitPoint(ref tempPoint, picV)) {
        //						picV.Dispose(); //释放相应的资源
        //						MessageBox.Show("此大板不能放下此图片,请另选一模板");
        //						return;
        //					}
        //					if (picV.IsWhirl) {
        //						picV.IsWhirl = false;
        //					}
        //					else {
        //						picV.IsWhirl = true;
        //					}
        //				}
        //				picV.Location = tempPoint;
        //				if (!picV.IsOutRedLine) {
        //					SetPicAtSuitPostion(picV);
        //				}
        //				else {
        //					AddPicToPanel(picV);
        //				}
        //			}
        //			if (overPicCount > 1) {
        //				//AutoPB_InBoard();
        //			}
        //		}
        //		internal void DrawPic(List<PhotoInfo_PinBan> photoList, Point mouseFormBigBoardPoint) //将拖到大板上的图片将其放到合适的位置
        //		{
        //			foreach(PhotoInfo_PinBan pinfo in photoList) {
        //				PicView picV = new PicView(pinfo, mouseFormBigBoardPoint);
        //				//GetSuitPoint(picV);
        //				Point tempPoint = picV.Location;
        //				if (!GetSuitPoint(ref tempPoint, picV)) {
        //					//旋转后再试
        //					int width, height;
        //					width = picV.Width;
        //					height = picV.Height;
        //					if (DataTransfer.curTemplate.HasBarCode) {
        //						if (DataTransfer.BarCodeStatus == 1) //条码在左右
        //						{
        //							width -= DataTransfer.BarCodePixWidth;
        //							height += DataTransfer.BarCodePixWidth;
        //						}
        //						else //条码在上下
        //						{
        //							width += DataTransfer.BarCodePixWidth;
        //							height -= DataTransfer.BarCodePixWidth;
        //						}
        //					}
        //					picV.Width = height;
        //					picV.Height = width;
        //					if (!GetSuitPoint(ref tempPoint, picV)) {
        //						MessageBox.Show("此大板不能放下此图片,请另选一模块");
        //						return;
        //					}
        //					picV.IsWhirl = true;
        //				}
        //				picV.Location = tempPoint;
        //				if (!picV.IsOutRedLine) {
        //					bool result = IsInRect(picV);
        //					if (result) {
        //						picV.Location = new Point(DataTransfer.inchBoardWidth + 10, 0);
        //					}
        //				}
        //				_ListPicView.Add(picV);
        //				pinfo.IsInBoard = true;
        //				picV.MouseDown += picV_MouseDown;
        //				picV.PicMoveEvent += picV_PicMoveEvent;
        //				picV.KeyPress += picV_KeyPress;
        //				picV._lblPName.MouseDown += _lblPName_MouseDown;
        //				picV._lblPSize.MouseDown += _lblPSize_MouseDown;
        //				_view.ShowPic(picV);
        //				ShowWraste();
        //			}
        //		}
        public Tb_paperTemplate_Info SelectedTemplate() //新建纸或是选择一个模板后
        {
            string strTemplateName = DataTransfer.PreSelectTemplateName;
            //            if (DataTransfer.curTemplate.TemplateName != strTemplateName)
            //            {
            if (string.IsNullOrEmpty(strTemplateName))
            {
                MessageBox.Show("请选择正确的模板！");
                return null;
            }
            Tb_paperTemplate_Info tempTemplate = DataTransfer.TemplateList.FirstOrDefault(pt => pt.TemplateName == strTemplateName);
            if (tempTemplate == null)
            {
                MessageBox.Show("请选择正确的模板！");
            }
            ClearBigBoard();
            if (tempTemplate.PaperFaceId != DataTransfer.curTemplate.PaperFaceId ||
                tempTemplate.PaperTypeId != DataTransfer.curTemplate.PaperTypeId)
            {
                //_isNewPhotoList = true;
                //根据模板绑定照片列表，以及左边的控件
                DataTransfer.curTemplate = tempTemplate;
                RushBindPhotos(_view.ShowAllPapertypePhotos);
            }
            else
            {
                DataTransfer.curTemplate = tempTemplate;
                //_isNewPhotoList = false;
            }

            //DataTransfer.BarCodeStatus = tempTemplate.HasBarCode ? 1 : 2;
            //纸型、纸面一样，但是尺寸不一样
            _view.InitCtlsLoaction();
            _view.DrawScaleLine();
            return DataTransfer.curTemplate;
            //            }
            //            else
            //            {
            //                //_isNewPhotoList = false;
            //            }
        }
        public void BindClearBoxList() //绑定清柜的列表
        {
            if (_photosList == null)
            {
                return;
            }
            if (_isNewPhotoList)
            {
                _clearBoxPhotos = _photosList.Where(p => p.IsClearBox == 1).ToList();
                //_curShowPhotoList = _photosList.Where(p => p.IsClearBox == 1).ToList();
                _isNewPhotoList = false;
            }
            else
            {
                if (_clearBoxPhotos == null || _clearBoxPhotos.Count < 1)
                {
                    _clearBoxPhotos = _photosList.Where(p => p.IsClearBox == 1).ToList();
                    //_curShowPhotoList = _photosList.Where(p => p.IsClearBox == 1).ToList();
                }
            }
            //_curShowPhotoList = _clearBoxPhotos;
            //BindDefaultPhotos();
            //BindPhotos(_clearBoxPhotos);
            //_view.BindMainGrid(_clearBoxPhotos);
            BindPhotos(_clearBoxPhotos);
        }
        internal void RushBindPhotos(bool showAllPapertypePhotos) //绑定照片到相应的控件中
        {
            RushBindPhotos(true, showAllPapertypePhotos);
        }
        ///// <summary>
        ///// 刷新
        ///// </summary>
        ///// <param name="refush">是否要从数据库取数据，true-是，false-不需要</param>
        //internal void RushBindPhotos(bool refush)
        //{
        //    ClearBigBoard();
        //    if (refush)
        //    {
        //        _isNewPhotoList = true;
        //        GetSuitPhotosByTemplate();
        //    }
        //    //BindPhotos(_photosList);
        //    BindDefaultPhotos();
        //}
        /// <summary>
        ///     刷新照片
        /// </summary>
        /// <param name="refush">是否要从数据库取数据，true-是，false-不需要</param>
        /// <param name="showAllPapertypePhotos">是否显示全部纸型的照片,true-是，false-不需要</param>
        internal void RushBindPhotos(bool refush, bool showAllPapertypePhotos)
        {
            ClearBigBoard();
            if (refush)
            {
                _isNewPhotoList = true;
                GetSuitPhotosByTemplate(showAllPapertypePhotos);
            }
            //BindPhotos(_photosList);
            BindDefaultPhotos();
        }
        internal void ClearBigBoard() //清空大板
        {
            foreach (PicView picv in _ListPicView)
            {
                PhotoInfo_PinBan piTemp = _photosList.Find(delegate(PhotoInfo_PinBan pi)
                {
                    if (pi.PhotoId == picv.PInfo.PhotoId)
                    {
                        return true;
                    }
                    return false;
                });
                if (piTemp != null)
                {
                    piTemp.IsInBoard = false;
                    piTemp.IsWhirl = false;
                }
            }
            _ListPicView.Clear();
            _view.ClearBigBoard();
        }
        internal void FilterShop() //筛选商户照片
        {
            string strSelectShopName = _view.SelectShop;
            string strSelectCtmName = _view.SelectCtmName;
            string strSelectOrderProductName = _view.SelectOrderProductName;
            if (!string.IsNullOrEmpty(strSelectShopName))
            {
                if (strSelectShopName.Equals("全部"))
                {
                    _curShowPhotoList = _photosList;
                }
                else
                {
                    _curShowPhotoList =
                        _photosList.Where(
                            p =>
                            p.ShopName == strSelectShopName && p.CtmName == (string.IsNullOrEmpty(strSelectCtmName) ? p.CtmName : strSelectCtmName) &&
                            p.OrderInfoName == (string.IsNullOrEmpty(strSelectOrderProductName) ? p.OrderInfoName : strSelectOrderProductName)).ToList();
                }
                //_view.BindMainGrid();
                //BindDefaultPhotos();
                _view.BindMainGrid(_curShowPhotoList);
            }
        }
        internal void FilterPhotoSize() //筛选片尺寸
        {
            string strSelectPhotoSize = _view.SelectPhotoSize;
            if (!string.IsNullOrEmpty(strSelectPhotoSize))
            {
                int inx = strSelectPhotoSize.IndexOf("*");
                string strPSTemp = strSelectPhotoSize.Substring(inx + 1) + "*" + strSelectPhotoSize.Substring(0, inx);
                _curShowPhotoList = _photosList.Where(p => p.PhotoSize == strSelectPhotoSize || p.PhotoSize == strPSTemp).ToList();
                //_view.BindMainGrid(_photosList.Where(p => p.PhotoSize == strSelectPhotoSize || p.PhotoSize == strPSTemp).ToList());
                //BindDefaultPhotos();
                _view.BindMainGrid(_curShowPhotoList);
            }
        }
        internal void PintCurBoard(IEnumerable<RectangeView> rectangeViews, float wraste) //打印当前大板
        {
            _curWraste = wraste;
            int result = 0;
            RectangeView[] enumerable = rectangeViews as RectangeView[] ?? rectangeViews.ToArray();
            int maxWidth = enumerable.Max(c => c.PixelX + c.PixelWidth);
            if (maxWidth < 1)
            {
                return;
            }
            int realBoardLength = maxWidth;///DataTransfer.CurPrinter.PDPI;
            //			PicView tP = _ListPicView.FirstOrDefault(pv => pv.Type == 1);
            //			if (tP != null) {
            //				MessageBox.Show("有框选图片，请单击空白处，再打印！");
            //				return;
            //			}
            List<PhotoInfo_PinBan> effectPiPinBan = enumerable.ToList().ConvertAll(c =>
            {
                PhotoInfo_PinBan r = new PhotoInfo_PinBan();
                r.Location = new Point(c.PixelX, c.PixelY);
                r.IsWhirl = c.isRotate == 1;
                r.PixHeight = r.IsWhirl ? c.PixelWidth : c.PixelHeight;
                r.PixWidth = r.IsWhirl ? c.PixelHeight : c.PixelWidth;
                r.PhotoId = c.PictureID;
                r.Priority = _photosList.FirstOrDefault(p => p.PhotoId == r.PhotoId).Priority;
                if (c.BarcodePlace == 0)
                {
                    r.BarCodeStatus = 1;
                }
                else if (c.BarcodePlace == 1)
                {
                    r.BarCodeStatus = 0;
                }
                else
                {
                    r.BarCodeStatus = c.BarcodePlace;
                }
                return r;
            });

            //			List<PhotoInfo_PinBan> effectPi_PinBan = _ListPicView.Where(pv => pv.IsOutRedLine == false && pv.Type != 1).Select(pv => pv.PInfo).ToList();
            if (effectPiPinBan.Count > 0)
            {
                result = _bll.CreateBoard(effectPiPinBan, DataTransfer.curTemplate, DataTransfer.CurPrinter, DataTransfer.curUid, _curWraste,
                                        realBoardLength, Properties.Settings.Default.BoardType);
                if (result == 1)
                {
                    MessageBox.Show("添加大板信息时出错！");
                }
                else if (result == -2) //加密是出错
                {
                    MessageBox.Show("与服务器连接失败！");
                }
                else if (result == -1) //拼板超出了范围
                {
                    effectPiPinBan.Clear(); //清出LJ
                    RushBindPhotos(true, _view.ShowAllPapertypePhotos);
                    ClearBigBoard();
                }
                else //result=0
                {
                    //1.清除大板上所有的图片，2清空ListPicView,3重新取得_photosList,
                    _photosList = _photosList.Except(effectPiPinBan).ToList();
                    effectPiPinBan.Clear(); //清出LJ
                    _curShowPhotoList = _photosList;
                    RushBindPhotos(false, _view.ShowAllPapertypePhotos);
                    ClearBigBoard();
                }
            }
        }
        internal void ShowImgChanged() //是否显示图片
        {
            foreach (PicView pv in _ListPicView)
            {
                pv.IilitialImg();
            }
        }
        internal void SelectTemplate() // 打开选择模板界面
        {
            FrmTemplate frmN = new FrmTemplate();
            DialogResult result = frmN.ShowDialog();
            if (result == DialogResult.OK)
            {
                BindTemplate();
                SelectedTemplate();
            }
        }

        //        internal void AutoPB()//自动拼板
        //        {
        //            if (_curShowPhotoList.Count > 1)
        //            {
        //                List<PhotoInfo_PinBan> listResult;
        //                ClearBigBoard();
        //				
        ////				_autoPb.AutoPinSN(_curShowPhotoList, DataTransfer.curTemplate, DataTransfer.CurPrinter, out waste, out currLength,,1);
        //				 
        //                listResult = _bll.AutoPinS(_curShowPhotoList, DataTransfer.curTemplate, DataTransfer.BarCodeStatus);
        //                if (listResult.Count > 0)
        //                {
        //                    ResolveAutoPBResult(listResult);
        //                }
        //            }
        //        }
        internal List<PhotoInfo_PinBan> semiAutoPB()
        {
            ClearBigBoard();
            decimal waste = 100, outWaste;
            int currLength, mode = 0;
            List<PhotoInfo_PinBan> rval;
            int minLength = (int)(DataTransfer.curTemplate.BoardLength * 0.7);
            //			var parallelLoopResult = Parallel.For(0, 2, new ParallelOptions() {MaxDegreeOfParallelism = 3}, i => {
            //				var rval1 = _autoPb.AutoPinSN(_curShowPhotoList, DataTransfer.curTemplate, DataTransfer.CurPrinter, out outWaste, out currLength, minLength, i);
            //				if (rval1.Count > 0 && outWaste < waste) {
            //					rval = rval1;
            //					waste = outWaste;
            //					mode = i;
            //				}
            //			});
            _autoPb.BARCODEWIDTH2 = DataTransfer.BarCodePixWidth;
            _bll.BARCODEWIDTH = DataTransfer.BarCodePixWidth;
            rval = _autoPb.AutoPinSN(_curShowPhotoList, DataTransfer.curTemplate, DataTransfer.CurPrinter, out outWaste, out currLength, minLength, 1);
            if (rval.Count > 0)
            {
                ResolveAutoPBResult(rval);
            }
            return rval;
        }
        internal void FAutoPB()
        { //全自动拼板
            ClearBigBoard();
            FrmAutoPinban frm = new FrmAutoPinban(DataTransfer.curUid);
            frm.ShowDialog();
            RushBindPhotos(_view.ShowAllPapertypePhotos);
        }
        internal void ClearDataTransferData() //在页面退出时清空缓存的数据
        {
            DataTransfer.CurPrinter = null;
            DataTransfer.curTemplate = null;
            DataTransfer.curUid = 0;
            DataTransfer.curUser = null;
            DataTransfer.IsShowWaste = false;
            DataTransfer.IsShowImg = false;
            DataTransfer.PreSelectTemplateName = null;
            DataTransfer.TemplateList = null;
        }
        internal void ShowConnectionFrm() //Show出通迅对话框
        {
            frmMain frm = frmMain.GetInstance(DataTransfer.curUid);
            frm.Show();
        }
        internal void SendToOtherPrinter() //将选中的照片转发给其它打印机
        {
            List<int> PIdList = _view.SelectPhotoIdList;
            if (PIdList.Count < 1)
            {
                return;
            }
            ZFSelectPrinter frmZF = new ZFSelectPrinter();
            frmZF.currPrintId = DataTransfer.CurPrinter.PrinterID;
            if (frmZF.ShowDialog() == DialogResult.OK)
            {
                int result = _bll.ZFPhoto(PIdList, frmZF.SelectedPrinterId);
                if (result != 1)
                {
                    MessageBox.Show("转发失败！");
                }
                else //转化成功，就刷新列表
                {
                    RushBindPhotos(true, _view.ShowAllPapertypePhotos);
                }
            }
        }

        #endregion

        #region 框选图片

        internal void MultiSelectedPic(PicView pv, List<PicView> selectedCtrls) //框选多张图片
        {
            //1.当新的大图PV加入到_ListPicView
            //2.改变被选图片的type=2
            //3.调整被选图片的相对坐标，及所属父容器
            //4.注册相应的事件，如移动，删除、mouseDown事件等
            //5.改变被选图片的相应事件
            _multilSelectTPicV = pv;
            _mulSelPicVList = selectedCtrls;
            Point p;
            pv.MouseDown += picV_MouseDown;
            pv.PicMoveEvent += picV_PicMoveEvent;
            pv.KeyPress += picV_KeyPress;
            _ListPicView.Add(pv);
            foreach (PicView pic in selectedCtrls)
            {
                pic.Type = 2;

                //取消事件
                pic.MouseDown -= picV_MouseDown;
                pic.PicMoveEvent -= picV_PicMoveEvent;
                pic.KeyPress -= picV_KeyPress;
                pic._lblPName.MouseDown -= _lblPName_MouseDown;
                pic._lblPSize.MouseDown -= _lblPSize_MouseDown;

                //加入事件
                pic.MouseDown += _lblPName_MouseDown;
                p = pic.Location;
                p.Offset(-pv.Location.X, -pv.Location.Y);
                pic.Location = p;
                pv.Controls.Add(pic);
            }
        }
        internal void CancelMutilSelect() //撤消多选
        {
            //			//删除多选产生的那个Temp图片
            //			//将被选的小图片改变状态、还原事件、还原坐标
            //			if (_mulSelPicVList != null && _multilSelectTPicV != null) {
            //				_ListPicView.Remove(_multilSelectTPicV);
            //				_multilSelectTPicV.Visible = false;
            //				foreach(PicView pic in _mulSelPicVList) {
            //					pic.Location = new Point(pic.Location.X + _multilSelectTPicV.Location.X, pic.Location.Y + _multilSelectTPicV.Location.Y);
            //					pic.Type = 0;
            //
            //					//      取消事件          
            //					pic.MouseDown -= _lblPName_MouseDown;
            //					pic._lblPName.MouseDown -= _lblPName_MouseDown;
            //					pic._lblPSize.MouseDown -= _lblPSize_MouseDown;
            //
            //					//添加事件
            //					pic.MouseDown += picV_MouseDown;
            //					pic.PicMoveEvent += picV_PicMoveEvent;
            //					pic.KeyPress += picV_KeyPress;
            //					pic._lblPName.MouseDown += _lblPName_MouseDown;
            //					pic._lblPSize.MouseDown += _lblPSize_MouseDown;
            //					_view.ShowPic(pic);
            //				}
            //				_multilSelectTPicV.Dispose();
            //				_multilSelectTPicV = null;
            //				_mulSelPicVList.Clear();
            //			}
        }

        #endregion

        private List<PhotoInfo_PinBan> otherMatPhotoInfo;
        //public void FillOtherMatPhoto(params int[] mid)
        //{
        //    foreach (PhotoInfo_PinBan photoInfoDdo in otherMatPhotoInfo)
        //    {
        //        _photosList.Remove(photoInfoDdo);
        //    }
        //    if (mid.Length > 0)
        //    {
        //        List<PhotoInfo_PinBan> data = _bll.GetWaitPBPhoto(DataTransfer.curTemplate.printerId, mid, DataTransfer.CurPrinter);

        //        foreach (PhotoInfo_PinBan p in data)
        //        {
        //            if (_photosList.All(c => c.PhotoId != p.PhotoId))
        //            {
        //                _photosList.Add(p);
        //                otherMatPhotoInfo.Add(p);
        //            }
        //        }
        //        RushBindPhotos(false, _view.ShowAllPapertypePhotos);
        //        //			_bll.ConvertPiToPi_PingBan(otherMatPhotoInfo.Select(c=>c.FillEntity()));
        //        //			_photosList.AddRange(photoInfoDdos);			}
        //    }
        //}

        internal List<PhotoInfo_PinBan> AdddXFfile(List<PhotoInfo_PinBan> listToSave)
        {
           return  _bll.AddDXF(listToSave);
        }

        internal List<PhotoInfo_PinBan> DeletedXFfile(List<PhotoInfo_PinBan> list)
        {
            return _bll.DelDXF(list);
        }
    }
}
